const httpStatus = require('http-status');
const ApiError = require('../utils/ApiError');
const catchAsync = require('../utils/catchAsync');
const { Tag } = require('../models');

/**
 * 创建新标签
 */
const createTag = catchAsync(async (req, res) => {
  // 检查标签名是否已被使用
  if (await Tag.isNameTaken(req.body.name)) {
    throw new ApiError(httpStatus.BAD_REQUEST, '标签名称已存在');
  }
  
  const tag = await Tag.create(req.body);
  res.status(httpStatus.CREATED).send(tag);
});

/**
 * 获取所有标签
 */
const getTags = catchAsync(async (req, res) => {
  const tags = await Tag.find({ isDeleted: false }).sort({ count: -1, createdAt: -1 });
  res.send(tags);
});

/**
 * 获取单个标签
 */
const getTag = catchAsync(async (req, res) => {
  const tag = await Tag.findOne({ _id: req.params.tagId, isDeleted: false });
  if (!tag) {
    throw new ApiError(httpStatus.NOT_FOUND, '标签不存在');
  }
  res.send(tag);
});

/**
 * 更新标签
 */
const updateTag = catchAsync(async (req, res) => {
  const tag = await Tag.findOne({ _id: req.params.tagId, isDeleted: false });
  if (!tag) {
    throw new ApiError(httpStatus.NOT_FOUND, '标签不存在');
  }
  
  // 检查新的标签名是否与其他标签重复
  if (req.body.name && await Tag.isNameTaken(req.body.name, req.params.tagId)) {
    throw new ApiError(httpStatus.BAD_REQUEST, '标签名称已存在');
  }
  
  Object.assign(tag, req.body);
  await tag.save();
  res.send(tag);
});

/**
 * 删除标签
 */
const deleteTag = catchAsync(async (req, res) => {
  const tag = await Tag.findOne({ _id: req.params.tagId, isDeleted: false });
  if (!tag) {
    throw new ApiError(httpStatus.NOT_FOUND, '标签不存在');
  }
  
  // 检查标签是否正在使用
  if (tag.count > 0) {
    throw new ApiError(httpStatus.BAD_REQUEST, '该标签正在使用中，无法删除');
  }
  
  // 逻辑删除
  tag.isDeleted = true;
  await tag.save();
  res.status(httpStatus.NO_CONTENT).send();
});

module.exports = {
  createTag,
  getTags,
  getTag,
  updateTag,
  deleteTag,
}; 